package com.fly.simple;

import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.fly.simple.utils.Executor;
import com.fly.simple.utils.RegExUtils;

/**
 * 快速启动
 */
public class Quickstart
{
    /**
     * 遍历jar目录下的zipkin-server-xxx-exec.jar,选择对应序号的jar启动<br>
     * java -jar quick-start-0.0.1.jar --port=8081
     * 
     * @param args
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException
    {
        String port = "9411";
        if (args.length > 0)
        {
            port = Stream.of(args).filter(arg -> arg.contains("--port")).map(arg -> arg.substring(arg.indexOf("=") + 1)).collect(Collectors.joining());
        }
        
        String path = new File("").getCanonicalPath();
        String[] files = new File(path).list();
        if (files != null && files.length > 0)
        {
            List<String> jarList = Stream.of(files)
                .filter(f -> f.endsWith("-exec.jar"))
                .sorted(Comparator.comparing(RegExUtils::getVersion)) // 自然数排序
                .collect(Collectors.toList());
            
            // 选项选择
            String input;
            Scanner sc = new Scanner(System.in);
            do
            {
                AtomicInteger count = new AtomicInteger(1);
                jarList.forEach(jar -> System.out.println(String.format("%2d ===> %s", count.getAndIncrement(), jar)));
                System.out.println("请输入序号选择文件，x退出：");
                input = sc.nextLine();
                if ("x".equalsIgnoreCase(input))
                {
                    System.out.println("退出系统!");
                    sc.close();
                    return;
                }
            } while (input == null || input.trim().length() == 0 || Integer.parseInt(input) < 1 || Integer.parseInt(input) > jarList.size());
            String jar = jarList.get(Integer.parseInt(input) - 1);
            System.out.println("你选择了：" + jar);
            
            // 执行脚本
            String command = String.format("java -jar %s --server.port=%s", jar, port);
            Executor.execute(command, false);
            sc.close();
            
            try
            {
                Runtime.getRuntime().exec("cmd /c start /min http://127.0.0.1:" + port);
            }
            catch (IOException e)
            {
            }
        }
    }
}
